package logic

import (
	"context"
	"net/http"
	"strconv"
	"week1/client/internal/svc"
	"week1/client/internal/types"
	"week1/ordersrv/ordersrv"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateOrderLogic) CreateOrder(req *types.CreateOrderReq) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	var (
		goodsDataInfo []*ordersrv.GoodsDetailInfo
	)
	//数据处理
	for _, goods := range req.GoodsDetailInfo {
		for i, v := range goods {
			goodsId, _ := strconv.Atoi(i)
			goodsDataInfo = append(goodsDataInfo, &ordersrv.GoodsDetailInfo{
				GoodId:  uint32(goodsId),
				GoodNum: uint32(v),
			})
		}
	}
	res, err := l.svcCtx.OrderRpc.CreateOrder(l.ctx, &ordersrv.CreateOrderReq{
		Userid:          req.Userid,
		OrderAddressId:  req.OrderAddressId,
		GoodsDetailInfo: goodsDataInfo,
	})
	if err != nil {
		return &types.Response{
			Code:    http.StatusInternalServerError,
			Message: err.Error(),
			Data:    nil,
		}, err
	}
	return &types.Response{
		Code:    http.StatusOK,
		Message: "order add success",
		Data: map[string]interface{}{
			"ordersn": res.OrderSn,
		},
	}, nil
}
